//
//  FQLoginViewController.m
//  WeChat
//
//  Created by 方桥 on 16/5/13.
//  Copyright © 2016年 方桥. All rights reserved.
//

#import "FQLoginViewController.h"
#import "AppDelegate.h"
#import "MBProgressHUD+HM.h"
@interface FQLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;

@end

@implementation FQLoginViewController
- (IBAction)LoginBtnClick:(id)sender {
    // 1.判断有没有输入用户名和密码
    if (self.userField.text.length == 0 || self.pwdField.text.length == 0) {
        FQLog(@"请输入用户名和密码");
        return;
    }
    // 给用户提示
    [MBProgressHUD showMessage:@"正在登录。。。"];
    // 2.登录服务器
    // 2.1把用户名和密码保存到沙盒
//    NSUserDefaults *deafults =[NSUserDefaults standardUserDefaults];
//    [deafults setObject:self.userField.text forKey:@"user"];
//    [deafults setObject:self.pwdField.text forKey:@"pwd"];
//    [deafults synchronize];
    [FQAccount shareAccount].user = self.userField.text;
    [FQAccount shareAccount].pwd = self.pwdField.text;
    
    
    __weak typeof(self) selfVc = self;
    // 2.2调用xmppLogin方法
    [FQXmppTool sharedFQXmppTool].registerOperation = NO;
    [[FQXmppTool sharedFQXmppTool] xmppLogin:^(XMPPResultType resultType) {
        
        [selfVc handleXMPPResultType:resultType];
        
    }];
}
-(void)handleXMPPResultType:(XMPPResultType)resultType
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        if (resultType == XMPPResultTypeLoginSucess) {//登录成功
            [MBProgressHUD showSuccess:@"登录成功"];
            //切换到主界面
            [self changeToMain];
            // 设置当前的登录状态
            [FQAccount shareAccount].login = YES;
            //保存登录账号到沙盒
            [[FQAccount shareAccount] saveToSandBox];
            
        }else{//登录失败
            [MBProgressHUD showError:@"登录失败"];
        }
    });
}
-(void)changeToMain
{
    
    // 1.获取Main.storyboard的第一个控制器
    id vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController];
    // 2.切换window的根控制器
    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
